﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Web;
using System.Web.Mvc;
using System.ServiceModel.Syndication;

namespace CoolCode.Web.Mvc
{
	public enum FeedType
	{
		Rss,
		Atom
	}

	public sealed class FeedResult : ActionResult
	{
		private FeedType type = FeedType.Rss;

		public SyndicationFeed Feed
		{
			get;
			set;
		}

		public FeedType Type
		{
			get { return type; }
			set { type = value; }
		}

		public FeedResult(SyndicationFeed syFeed, FeedType type)
		{
			this.Feed = syFeed;
			this.type = type;
		}

		public override void ExecuteResult(ControllerContext context)
		{
			//输出
			context.HttpContext.Response.ContentType = "text/xml;charset=utf-8";
			if (type == FeedType.Rss)
			{
				Rss20FeedFormatter rssFormat = new Rss20FeedFormatter(Feed);
				XmlWriter rssWriter = new XmlTextWriter(context.HttpContext.Response.OutputStream, System.Text.Encoding.UTF8);
				rssFormat.WriteTo(rssWriter);
				rssWriter.Close();
			}
			else if (type == FeedType.Atom)
			{
				Atom10FeedFormatter atomFormat = new Atom10FeedFormatter(Feed);
				XmlWriter atomWriter = new XmlTextWriter(context.HttpContext.Response.OutputStream, System.Text.Encoding.UTF8);
				atomFormat.WriteTo(atomWriter);
				atomWriter.Close();
			}
		}
	}
}
